<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 调拨出库
 * @package app\cms\admin
 */
class Allocation extends Admin
{

    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map1 = $this->getMap();
        $map2 = $this->getMap();
        //数据获取
        $data = input();
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		
		// $map1 = [];
		// $map2 = [];
		if($sotre_user['store_uid'] > 0){
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$warehouse_id = $store_warehouse_list[0];
			$map1[] = ['from_warehouse_id', '=', $warehouse_id];
			$map2[] = ['to_warehouse_id', '=', $warehouse_id];
		}
		
		//tab
        $list_tab = [
            'tab1' => ['title' => '申请中', 'url' => url('index', ['group' => 'tab1'])],
            'tab2' => ['title' => '已出库', 'url' => url('index', ['group' => 'tab2'])],
            'tab4' => ['title' => '已入库', 'url' => url('index', ['group' => 'tab4'])],
			'tab3' => ['title' => '已取消', 'url' => url('index', ['group' => 'tab3'])],
        ];

        // 数据列表
        $group = isset($data['group']) ? $data['group'] : 'tab1';
        switch ($group) {
            case 'tab1':
                $map1[] = ['all_status', '=', 0];
                $map2[] = ['all_status', '=', 0];
                break;
            case 'tab2':
                $map1[] = ['all_status', '=', 2];
                $map2[] = ['all_status', '=', 2];
                break;
            case 'tab3':
                $map1[] = ['all_status', '=', 3];
                $map2[] = ['all_status', '=', 3];
                break;
			case 'tab4':
                $map1[] = ['all_status', '=', 4];
                $map2[] = ['all_status', '=', 4];
                break;
        }
		
        //数据列表
		$data_list =  model('ErpAllocation') -> whereOr([$map1, $map2]) -> order('create_time desc') -> paginate();//获取列表
		foreach($data_list as $key => $value){
			// $data_list[$key]['nick_name'] 		= model('user_center/Member', 'model\user') -> find($value['uid']) -> nick_name;
			$data_list[$key]['nick_name'] 		= model('app\user\model\User') -> find($value['uid']) -> nickname;
			$data_list[$key]['from_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$value['from_warehouse_id'],'title');
			$data_list[$key]['to_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$value['to_warehouse_id'],'title');
		}
		
		$btn_details = [
			'title' => '详情',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('details', ['id' => '__id__']),
		];
		
		$btn_add = [
			'title' => '出库操作',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('outgoing', ['id' => '__id__']),
			'data-title' => '确定要出库吗？'
		];
		$btn_cancel = [
			'title' => '取消出库',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('cancelgoing', ['id' => '__id__']),
			'data-title' => '确定要取消出库吗？'
		];
		
		$btn_access = [
			'title' => '创建调拨单',
			'icon'  => 'fa fa-plus-circle',
			'class' => 'btn btn-primary',
			'href'  => url('add'),
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('调拨单列表')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_allocation') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['nick_name', '调拨申请人'],
                ['from_warehouse', '调出仓'],
                ['to_warehouse', '调入仓'],
                ['code', '调拨单号'],
                // ['remark', '备注'],
                ['handled_by', '经办人'],
                ['all_status', '调拨状态', 'status' , '', [0 => '申请中:warning', 2 => '已出库:success', 3 => '取消出库:default', 4 => '已入库:info']],//0申请中 1已审核 2已出库 3取消出库 4已入库
                ['create_time', '创建时间', 'datetime'],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([
				['text', 'code', '调拨单号', 'like'],
                ['text', 'handled_by', '经办人', 'like'],
				// ['select', 'all_status', '调拨单状态', '', '', [0 => '申请中', 2 => '已出库', 3 => '已取消', 4 => '已入库']],
				['daterange', 'create_time', '创建时间'],
            ])
			->addTopButton('custom', $btn_access) // 添加授权按钮
            ->addRightButton('btn_add', $btn_add, true) // 批量添加右侧按钮
            ->addRightButton('btn_cancel', $btn_cancel) // 批量添加右侧按钮
            ->addRightButton('custom', $btn_details, true) // 批量添加右侧按钮
			->replaceRightButton(['all_status' => 2], '', ['btn_add', 'btn_cancel'])
			->replaceRightButton(['all_status' => 4], '', ['btn_add', 'btn_cancel'])
			->replaceRightButton(['all_status' => 3], '', ['btn_add', 'btn_cancel'])
			->setTabNav($list_tab,  $group)
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 添加
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add(){
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
            $from_warehouse_id 	= isset($data['from_warehouse_id']) ? $data['from_warehouse_id'] : [];
            $to_warehouse_id 	= isset($data['to_warehouse_id']) ? $data['to_warehouse_id'] : [];
			$handled_by			= isset($data['handled_by']) ? $data['handled_by'] : '';
			$remark 			= isset($data['remark']) ? $data['remark'] : '';
			
			if($from_warehouse_id == '') $this->error('请选择调出仓库');
			if($to_warehouse_id == '') $this->error('请选择调入仓库');
			if($handled_by == '') $this->error('请输入经办人');
			
			$data['from_warehouse_id'] 	= $from_warehouse_id;
			$data['to_warehouse_id'] 	= $to_warehouse_id;
			$data['handled_by'] 		= $handled_by;
			$data['remark'] 			= $remark;
			$data['uid']  				= UID;
			$res = model('ErpAllocationLinshi') -> isUpdate(false) ->data($data, true) -> save();
			$id = model('ErpAllocationLinshi') -> id;
			//选择商品
			$this->redirect('add_goods', ['allocation_id' => $id, 'from_warehouse_id' => $from_warehouse_id]);
        }
		
		$uid = UID;//后台管理员ID
		$sotre_user = model('app\user\model\User') -> find($uid);//获取列表
		$map = [];
		$map[] = ['type', '=', 1];
		if($sotre_user['store_uid'] > 0){
			//根据门店id 查询出仓库的id
			$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($sotre_user['store_id']);
			foreach ($warehouse_list['data'] as $key => $value) {
				if($value['type'] == 1){//分店仓库
					$store_warehouse_list[] = $value['wid'];
				}
			}
			$map[] = ['id', 'in', $store_warehouse_list];
		}else{
			$store_warehouse_list[0] = '';
		}
		$warehouse_list	= model('ErpWarehouse') -> where($map) -> column('id,title');
		$from_warehouse_list = model('ErpWarehouse') -> where('type', 2) -> column('id,title');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('调拨单申请') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
				['select', 'from_warehouse_id', '调出仓库', '请选择仓库', $from_warehouse_list, key($from_warehouse_list)],
				['select', 'to_warehouse_id', '调入仓库', '请选择仓库', $warehouse_list, $store_warehouse_list[0]],
				['text', 'handled_by', '经办人', '', get_nickname(UID)],
				['text', 'remark', '调拨单备注'],
            ])
			->setBtnTitle(['submit' => '下一步'])
			->isAjax(false)	
            ->fetch();
    }
	
	/**
     * 选择商品
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods($allocation_id = '', $from_warehouse_id = ''){
        // 保存数据
        if ($this->request->isPost()) {
			$sku_id = input('post.ids/a');
			//插入单品
			$list = [];
			foreach($sku_id as $sku_id){
				$map = [];
				$map['allocation_id'] = $allocation_id;
				$map['sku_id'] = $sku_id;
				$sku_linshi = model('ErpAllocationSkuLinshi') -> where($map) -> find();
				if(empty($sku_linshi)){
					$list[] = ['allocation_id' => $allocation_id,'sku_id' => $sku_id];
				}
			}
			$res = model('ErpAllocationSkuLinshi')->saveAll($list);
			$this->success('新增成功');
		}
		/*仓库中有库存的商品*/
		//获取筛选
        $map = $this->getMap();
		$map = [];
		$map['allocation_id'] = $allocation_id;
		$sku_linshi = model('ErpAllocationSkuLinshi') -> where($map) -> column('sku_id');
		
		$map = [];
		$map[] = ['warehouse_id', '=', $from_warehouse_id];
		$map[] = ['available_num', '>', 0];
		$map[] = ['sku_id', 'not in', $sku_linshi];
		$stock_num = model('ErpGoodsWarehouseStockNum') -> where($map) -> column('sku_id,goods_id');
		
		$data_list = [];
		foreach($stock_num as $key => $value){
			$goods = model('ErpGoods') -> find($value);
			
			$map = [];
			$map['warehouse_id'] = $from_warehouse_id;
			$map['sku_id'] 		 = $key;
			$available_num = model('ErpGoodsWarehouseStockNum') -> where($map) -> find() -> available_num;
			
			$goods_sku = model('ErpGoodsSku') -> find($key);
			$data_list[$key]['id'] 						= $goods_sku['id'];
			$data_list[$key]['goods_name'] 				= $goods_sku['goods_name'];
			$data_list[$key]['goods_specifications'] 	= $goods_sku['goods_specifications'];
			$data_list[$key]['price'] 					= $goods_sku['purchase_price'];
			$data_list[$key]['available_num'] 			= $available_num;
		}
		
        $add_goods_sku = [
			'title' => '新增',
			'class' => 'btn btn-primary ajax-post',
            'href'  => url('add_goods',['allocation_id' => $allocation_id])
        ];
		$sku_see = [
			'title' => '已选择商品',
			'class' => 'btn btn-success',
            'href'  => url('add_goods_stock',['allocation_id' => $allocation_id, 'from_warehouse_id' => $from_warehouse_id])
        ];
		$sku_submit = [
			'title' => '新增',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-primary ajax-get',
			'href'  => url('add_goods_sku', ['allocation_id' => $allocation_id, 'ids' => '__id__']),
		];
		
		return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('调拨单申请')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_sku') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_name', '商品名称'],
                ['goods_specifications', '规格'],
                ['price', '价格'],
                ['available_num', '可调拨数量'],
				['right_button', '操作', 'btn']
            ])
            // ->setSearch(['goods_name' => '商品名', 'goods_specifications' => '单品名称']) // 设置搜索参数
			->addTopButton('custom', $add_goods_sku) // 添加授权按钮
			->addTopButton('custom', $sku_see, true) // 添加授权按钮
			->addRightButton('sku_submit', $sku_submit) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 新增商品
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
	public function add_goods_sku($allocation_id = '', $ids = []){
		$sku_id = explode(',', $ids);
		//插入单品
		$list = [];
		foreach($sku_id as $sku_id){
			$map = [];
			$map['allocation_id'] = $allocation_id;
			$map['sku_id'] = $sku_id;
			$sku_linshi = model('ErpAllocationSkuLinshi') -> where($map) -> find();
			if(empty($sku_linshi)){
				$list[] = ['allocation_id' => $allocation_id,'sku_id' => $sku_id];
			}
		}
		$res = model('ErpAllocationSkuLinshi')->saveAll($list);
		$this->success('新增成功');
	}
	
	/**
     * 商品调拨数量
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods_stock($allocation_id = '', $from_warehouse_id = ''){
        $map = [];
		$map['allocation_id'] = $allocation_id;
		$data_list = model('ErpAllocationSkuLinshi') -> where($map) -> order('create_time desc') -> paginate();
		
		foreach($data_list as $key => $value){
			$map = [];
			$map['warehouse_id'] = $from_warehouse_id;
			$map['sku_id'] 		 = $value['sku_id'];
			$available_num = model('ErpGoodsWarehouseStockNum') -> where($map) -> find() -> available_num;
			
			$sku_info = model('ErpGoodsSku') -> find($value['sku_id']);//获取列表
			$data_list[$key]['goods_name'] 				= $sku_info['goods_name'];
			$data_list[$key]['goods_specifications'] 	= $sku_info['goods_specifications'];
			$data_list[$key]['price'] 					= $sku_info['purchase_price'];
			$data_list[$key]['available_num'] 			= $available_num;
		};
		
		$add_purchase = [
			'title' => '提交调拨申请',
			'class' => 'btn btn-primary ajax-get confirm',
            'href'  => url('add_purchase_submit',['allocation_id' => $allocation_id]),
        ];
		
        return ZBuilder::make('table') // 设置页面标题
			->setPageTitle('调拨数量')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_goods_allocation_sku_linshi') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', '规格id'],
                ['goods_name', '商品名称'],
                ['goods_specifications', '规格名'],
                ['price', '价格'],
                ['available_num', '可用调拨数量'],
                ['num', '调拨数量', 'text.edit'],
                ['right_button', '操作', 'btn']
            ])
			->addTopButton('delete') // 添加顶部按钮
			->addTopButton('custom', $add_purchase) // 添加授权按钮
			->addRightButton('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }
	
	/**
     * 提交调拨申请
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
	public function add_purchase_submit($allocation_id = ''){
		DB::startTrans();//启动事务
		$allocation_linshi = model('ErpAllocationLinshi') -> find($allocation_id); // 采购单详情
		$sku_linshi = model('ErpAllocationSkuLinshi') -> where('allocation_id', $allocation_id) -> column('id,sku_id,num'); // 采购单详情
		if(empty($sku_linshi)){
			DB::rollback();
			$this->error('请选择需要调拨的商品');
		}
		$user_id 				= $allocation_linshi['uid'];
		$from_warehouse_id 		= $allocation_linshi['from_warehouse_id'];
		$to_warehouse_id 		= $allocation_linshi['to_warehouse_id'];
		$remark 				= $allocation_linshi['remark'];
		$handled_by 			= $allocation_linshi['handled_by'];
		
		$code_count = model('ErpAllocation') ->count();
        $code = 'A'.date('Ymd').(str_pad(($code_count+1),3,"0",STR_PAD_LEFT));
		$rel = model('ErpAllocation') -> addData($user_id, $from_warehouse_id, $to_warehouse_id, $remark, $handled_by, $code);//添加
		if($rel['code'] < 0){
			DB::rollback();
			$this->error($rel['message'], cookie('__forward__'));
		}
		
		//插入调拨 sku参数
		$sku_arr = [];
		$sku_linshi_id = [];
		$a_id = $rel['data'];
		foreach($sku_linshi as $key => $value){
			if($value['num'] == 0 || $value['num'] == ''){
				DB::rollback();
				$this->error('请输入调拨单中所有商品的调拨数量');
			}
			
			//货物数量校验-先更新再查
			$rel_upnum = model('ErpGoodsWarehouseStockNum') -> editDataForAllocation($from_warehouse_id, $value['sku_id'], $value['num']);
			if($rel_upnum['code'] == 200){
				//更新完查询如果小于0 则回滚
				$map_ishave = [];
				$map_ishave[] = ['warehouse_id', '=', $from_warehouse_id];
				$map_ishave[] = ['sku_id', '=', $value['sku_id']];
				$res_ishave = model('ErpGoodsWarehouseStockNum')->where($map_ishave)->find();//dump($res_ishave);
				if($res_ishave['available_num'] < 0){
					DB::rollback();
					$this->error('库存不足');
				}
			}else{
				DB::rollback();
				$this->error('库存不足, SKU_id:'.$value['sku_id']);
			}
			
			$sku_info = model('ErpGoodsSku') -> find($value['sku_id']);//获取列表
			$sku_arr[] = [
				'allocation_id' => $a_id,
				'sku_id'	    => $value['sku_id'],
				'num'	  	    => $value['num'],
				'price'	  	    => $sku_info['purchase_price'],
			];
			$sku_linshi_id[] = $key;
		}
		
		$rel = model('ErpAllocationSku') -> saveAll($sku_arr);//dump($rel);

		if(!$rel < 0){
			DB::rollback();
			$this->error('插入失败，请重试', cookie('__forward__'));
		}
		
		model('ErpAllocationLinshi') -> destroy($allocation_id);
		model('ErpAllocationSkuLinshi') -> destroy($sku_linshi_id);
		
		DB::commit();
		$this->success('调拨申请成功', url('allocation/index'), '_parent_reload');
	}
	
	//调拨单详情
	public function details($id = []){
		$info = model('ErpAllocation') -> find($id);
		
		switch ($info['all_status']) {
			case 0;
				$info['all_status'] = '申请中';
				break;
			case 1;
				$info['all_status'] = '已审核';
				break;
			case 2;
				$info['all_status'] = '已出库';
				break;
			case 3;
				$info['all_status'] = '取消出库';
				break;
			case 4;
				$info['all_status'] = '已入库';
				break;
		}
		
		$table_data = [
			['sku_id', '调拨商品', '调拨申请数量', '实际出库数量', '出库备注'],
		];
		
		$info['nick_name'] 		= model('app\user\model\User') -> find($info['uid']) -> nickname;;
		$info['from_warehouse'] = get_nick_name('1','ErpWarehouse','id',$info['from_warehouse_id'],'title');
		$info['to_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$info['to_warehouse_id'],'title');
		
		$allocation_sku = model('ErpAllocationSku') -> where('allocation_id', $id) -> column('sku_id,num,ck_num,ck_remark');
		foreach($allocation_sku as $key => $value){
			$goods_info = model('ErpGoodsSku') -> find($key);
			if($goods_info['goods_specifications'] != ''){
				$goods_name = $goods_info['goods_name'] . ' - ' . $goods_info['goods_specifications'];
			}else{
				$goods_name = $goods_info['goods_name'];
			}
			
			$table_data[] = [$key, $goods_name, $value['num'], $value['ck_num'], $value['ck_remark']];
		}
		
		$ware_info = model('ErpGoodsWarehousing') -> where('code', $info['code']) -> find();
		$info['ck_remark'] = $ware_info['remark'];
		$info['ck_handled_by'] = $ware_info['handled_by'];
		//批量审核最多允许20个
		return ZBuilder::make('form')
            ->setPageTitle('调拨单详情') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
				['text', 'nick_name', '申请调拨人', '', '', '', 'readonly="readonlys"'],
				['text', 'code', '调拨单号', '', '', '', 'readonly="readonlys"'],
				['text', 'from_warehouse', '调出仓', '', '', '', 'readonly="readonlys"'],
				['text', 'to_warehouse', '调入仓', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '调拨备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '调拨经办人', '', '', '', 'readonly="readonlys"'],
				['complexTable', 'list_user', '调拨单sku', $table_data],
				['text', 'ck_remark', '出库备注', '', '', '', 'readonly="readonlys"'],
				['text', 'ck_handled_by', '出库经办人', '', '', '', 'readonly="readonlys"'],
				
			])
			->hideBtn(['submit', 'back'])
			->setFormData($info) // 设置表单数据
            ->fetch();
	}
	
	
	/**
     * 调拨单出库
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
    public function outgoing($id = ''){
		DB::startTrans();//启动事务
		
		if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');
			
			$rk_remark      = isset($data['rk_remark']) ? $data['rk_remark'] : '';
            $rk_handled_by  = isset($data['rk_handled_by']) ? $data['rk_handled_by'] : '';
			if($rk_handled_by == '') $this->error('请输入出库经办人');
			
			unset($data['__token__']);
			unset($data['nick_name']);
			unset($data['from_warehouse']);
			unset($data['to_warehouse']);
			unset($data['code']);
			unset($data['remark']);
			unset($data['handled_by']);
			unset($data['rk_remark']);
			unset($data['rk_handled_by']);
			
			//校验采购单
			$order_code = model('ErpAllocation') -> find($id);
			if(empty($order_code) || $order_code['all_status'] > 0){
				DB::rollback();
			    $this->error('不存在调拨单');
			}
			
			//调拨出库操作 - 插入操作记录
			$code 			= $order_code['code'];
			$warehouse_id 	= $order_code['from_warehouse_id'];//仓库id
			$rel = model('ErpGoodsWarehousing', 'model') -> addData(2, $id, $rk_handled_by, $rk_remark, $code);
			if($rel['code'] < 0){
				DB::rollback();
				$this->error($rel['message']);
			}
			//组合数据
			$sku_arr = [];
			foreach($data as $key => $value){
				$sku_info = explode('/', $key);
				$sku_id   = $sku_info[1]; //商品skuid
				
				$map = [];
				$map['allocation_id'] = $id;
				$map['sku_id'] 		  = $sku_id;
				$purchase_sku = model('ErpAllocationSku') -> where($map) -> find();
				
				//组合sku信息
				$sku_arr[$sku_id]['id'] 	= $purchase_sku['id'];
				$sku_arr[$sku_id]['sku_id'] = $sku_id;
				
				if($sku_info[0] == 'rk_num'){
					if($value == ''){
						DB::rollback();
						$this->error('请输入商品出库数量！');
					} 
					if($value > $purchase_sku['num']){
						DB::rollback();
						$this->error('实际出库数量不能超过调拨单申请出库数量！');
					}
					$sku_arr[$sku_id]['ck_num'] = $value;
				}
				
				if($sku_info[0] == 'remark'){
					$sku_arr[$sku_id]['ck_remark'] = $value;
				}	
			}
			//插入实际出库数量
			$rel = model('ErpAllocationSku') -> saveAll($sku_arr);//dump($rel);
			if(!$rel){
				DB::rollback();
				$this->error('插入失败，请重试');
			}
			//出库 更新库存
			$rel = model('ErpAllocation') -> editDataOutGoing($id,'2');
			if($rel['code'] == 200){
				$rel = model('ErpAllocation') -> outGoing($id);//调出仓 出库减库存
				if($rel['code'] < 0){
					$this->error($rel['message']);
				}
				$rel = model('ErpAllocation') -> frozenGoing($id);//调入仓 入库 增加冻结库存
				if($rel['code'] < 0){
					$this->error($rel['message']);
				}
				
				DB::commit();
				$this->success('出库成功', cookie('__forward__'), '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
		
		$goods_sku_id = model('ErpAllocationSku') -> where('allocation_id', $id) -> column('sku_id,num');
		$table_data = [
			['调拨商品', '调拨申请数量', '实际出库数量', '备注'],
		];
		foreach($goods_sku_id as $key => $value){
			$sku_info = model('ErpGoodsSku') -> find($key);
			if($sku_info['goods_specifications'] != ''){
				$goods_name = $sku_info['goods_name'] . ' - ' . $sku_info['goods_specifications'];
			}else{
				$goods_name = $sku_info['goods_name'];
			}
			$table_data[] = [$goods_name, $value, '<input type="text" name="rk_num/'. $sku_info['id'] .'" />', '<input type="text" name="remark/'. $sku_info['id'] .'" />'];
		}
		
		$info = model('ErpAllocation') -> find($id);
		$info['nick_name'] 		= model('app\user\model\User') -> find($info['uid']) -> nickname;
		$info['from_warehouse'] = get_nick_name('1','ErpWarehouse','id',$info['from_warehouse_id'],'title');
		$info['to_warehouse'] 	= get_nick_name('1','ErpWarehouse','id',$info['to_warehouse_id'],'title');
       // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('出库单 - 出库操作') // 设置页面标题
            ->addFormItems([
				['text', 'nick_name', '出库操作人', '', '', '', 'readonly="readonlys"'],
				['text', 'from_warehouse', '调出仓', '', '', '', 'readonly="readonlys"'],
				['text', 'to_warehouse', '调入仓', '', '', '', 'readonly="readonlys"'],
				['text', 'code', '调拨单号', '', '', '', 'readonly="readonlys"'],
				['text', 'remark', '调拨备注', '', '', '', 'readonly="readonlys"'],
				['text', 'handled_by', '调拨经办人', '', '', '', 'readonly="readonlys"'],
				['text', 'rk_remark', '出库备注'],
				['text', 'rk_handled_by', '出库经办人', '', get_nickname(UID)],
			])
			->setFormData($info) // 设置表单数据
			->addFormItems([ // 批量添加表单项
				['complexTable', 'list_user', '调拨单sku', $table_data]
			])
            ->fetch();
    }
	
	/**
     * 取消出库
     * @author  shiqiang
     * @return mixed
     * @throws \think\Exception
     */
	public function cancelgoing($id = ''){
		$rel = model('ErpAllocation') -> editDataOutGoing($id,'3');
		if($rel['code'] == 200){
			$rel = model('ErpAllocation') -> cancelGoing($id);//取消出库增加库存
		}else{
			$this->error($rel['message']);
		}
		$this->success('取消成功', cookie('__forward__'));
	}
}